import { constantRoutes } from '@/router'
import { getRouters, findTopMenu } from '@/api/menu'
import Layout from '@/layout/index'
import ParentView from '@/components/ParentView';

const permission = {
  state: {
    topMenus: [],
    routes: [],
    leftMenus: [],
    activeTopMenu: localStorage.getItem('parentCode')
  },
  mutations: {
    SET_TOP_MENU: (state, menu) => {
      state.topMenus = menu;
    },
    UPDATE_TOP_MENU: (state, { index, dataKey, updateData }) => {
      state.topMenus[index][dataKey] = updateData
    },
    SET_AICTIV_TOP_MENU: (state, menuCode) => {
      state.activeTopMenu = menuCode;
      localStorage.setItem('parentCode', menuCode); // 缓存菜单code到本地
    },
    SET_ROUTES: (state, routes) => {
      state.routes = constantRoutes.concat(routes)
    },
    SET_LEFT_MENU: (state, leftmenu) => {
      state.leftMenus = constantRoutes.concat(leftmenu);
    },
  },
  actions: {
    // 生成路由
    GenerateRoutes({ state, commit }) {
      return new Promise(async (resolve) => {
        // 第一步：获取顶部菜单
        let { status, data } = await findTopMenu();
        if (status == 200) {
          commit('SET_TOP_MENU', data);

          // 第二步：通过顶部菜单code获取所有路由
          let allRouterRequset = state.topMenus.map(item => {
            let param = {
              parameter: {
                parentCode: item.menuCode
              }
            }
            return getRouters(param)
          })
          let allMenus = [];

          Promise.all(allRouterRequset).then(resList => {
            resList.forEach((res, index) => {
              if (res.status == 200) {
                allMenus = [...allMenus, ...res.data]; // 用于页面权限
                let handleRouters = filterAsyncRouter(res.data); // 处理路由
                let updateParams = {
                  index,
                  dataKey: 'routers',
                  updateData: handleRouters
                }
                commit('UPDATE_TOP_MENU', updateParams); // 将路由保存到对应的topMenus中去
              } else { // 如果获取失败添加空数组
                let updateParams = {
                  index,
                  dataKey: 'routers',
                  updateData: []
                }
                commit('UPDATE_TOP_MENU', updateParams);
              }
            })

            // 缓存页面权限
            localStorage.setItem('allMenu', JSON.stringify(allMenus));

            // 当前选中顶部导航，并加载左导航菜单
            let currentTopMenuCode = state.activeTopMenu ? state.activeTopMenu : state.topMenus[0].menuCode;
            commit('SET_AICTIV_TOP_MENU', currentTopMenuCode);
            let currentTopMenu = state.topMenus.find(item => item.menuCode === currentTopMenuCode);
            if (currentTopMenu) {
              let leftmenu = currentTopMenu.routers;
              commit('SET_LEFT_MENU', leftmenu);
            }

            // 添加所有路由
            let accessedRoutes = [];
            state.topMenus.forEach(topmenu => {
              accessedRoutes = [...accessedRoutes, ...topmenu.routers]
            })
            accessedRoutes.push({ path: '*', redirect: '/404', hidden: true });
            // console.log(state.topMenus);
            commit('SET_ROUTES', accessedRoutes);
            resolve(accessedRoutes);
          })

        }
      })
    },
    // 处理左导航菜单
    handleLeftMenus({ state, commit }, menuCode) {
      // 当前选中顶部菜单
      commit('SET_AICTIV_TOP_MENU', menuCode);

      // 根据顶部菜单code 加载对应左导航菜单
      let currentTopMenu = state.topMenus.find(item => item.menuCode === menuCode);
      if (currentTopMenu) {
        let leftmenu = currentTopMenu.routers;
        commit('SET_LEFT_MENU', leftmenu);
      }
      // console.log(state.leftMenus)
    }
  }
}

// 遍历后台传来的路由字符串，转换为组件对象
export function filterAsyncRouter(asyncRouterMap) {
  return asyncRouterMap.filter(route => {
    if (route.component) {
      // Layout ParentView 组件特殊处理
      if (route.component === 'Layout') {
        route.component = Layout
      } else if (route.component === 'ParentView') {
        route.component = ParentView
      } else {
        route.component = loadView(route.component)
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    return true
  })
}

export const loadView = (view) => { // 路由懒加载
  return (resolve) => require([`@/views/${view}`], resolve)
}

export default permission
